from urllib import request
import re
import os
import requests

class Role():

    def __init__(self,name,img,country):
        self.name = name
        self.img = img
        self.country = country

    def __str__(self) -> str:
        return f'名字：{self.name}\t头像：{self.img}\t所属区域：{self.country}'


class Spider():

    url = 'https://www.win3000.com/zt/ystpzq/'

    #发送请求，获取html
    def __fetch_content(self):
        r = request.urlopen(Spider.url) #打开url
        html = r.read()#读取内容，默认为byte格式
        # print(htmls)
        html = str(html,encoding='utf-8')#转成字符串格式
        # print(htmls)
        return html

    #分析html，使用正则表达式
    def __analysis(self,html):
        root_html = re.findall('<!-- 专题模块 -->([\s\S]*?)<!-- footer -->',html)
        root_html = root_html[0].replace('\n','').replace(' ','')
        country_html = re.findall('<divclass="zt-tit-box"><pclass="tit-name">原神([\s\S]*?)</a></h3></div></li></div>',root_html)
        role_list = []
        for roles_html in country_html:
            country = roles_html[0:2]
            roles_html = re.findall('笔记.md-src="([\s\S]*?)/></a>', roles_html)
            for role_html in roles_html:
                name = re.findall('"alt="([\s\S]*?)"',role_html)[0]
                img = re.findall('([\s\S]*?)"alt="',role_html)[0]
                role_list.append(Role(name,img,country))
        return role_list

    #下载图片
    def download_img(self,roles):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
        }
        path = './原神/'
        for role in roles:
            path = path + role.country
            if not os.path.exists(path):
                os.makedirs(path)
            r = requests.get(role.img, headers=headers)
            f = open(path+'/'+role.name+'.png', 'wb')
            f.write(r.content)
            f.close()
            path = './原神/'

    #入口方法
    def go(self):
        html = self.__fetch_content()
        role_list = self.__analysis(html)
        self.download_img(role_list)

if __name__ == '__main__':
    spider = Spider()
    spider.go()
